﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.IO;
using System.Net;
using System.Drawing;
using System.Runtime.Serialization.Formatters.Binary;

namespace Networking
{
    public delegate void ImageReceivedEventHandler(object sender, ImageReceivedEventArgs e);

    public class Server
    {
        public event ImageReceivedEventHandler Received;
        protected virtual void ImageReceived(ImageReceivedEventArgs e)
        {
            if (Received != null)
                Received(this, e);
        }

        Thread thread;

        TcpListener listener;
        bool ServerIsRunning;

        public Server(string IP, int port)
        {
            listener = new TcpListener(IPAddress.Parse(IP), port);
        }

        public void Begin()
        {
            thread = new Thread(new ThreadStart(RunServer));
            thread.Start();
        }

        TcpClient connectedClient;

        public void RunServer()
        {
            ServerIsRunning = true;
            while (ServerIsRunning)
            {
                listener.Start();

                if (listener.Pending() && connectedClient == null)
                {
                    connectedClient = listener.AcceptTcpClient();
                    if (connectedClient.Connected)
                    {
                        Console.WriteLine("I am connected!");
                        ReceiveImages();
                    }
                    else
                    {
                        connectedClient = null;
                    }
                }
            }

            Console.WriteLine("Ended");
        }

        protected void ReceiveImages()
        {
            Console.WriteLine("Receiving image");
            while (true)
            {
                NetworkStream stream = connectedClient.GetStream();
                BinaryFormatter formatter = new BinaryFormatter();
                Bitmap bitmap = (Bitmap)formatter.Deserialize(stream);

                ImageReceived(new ImageReceivedEventArgs(bitmap));
            }
        }
    }
}
